package com.dmcloud.common.util.auth;

import com.dmcloud.common.util.tools.WebUtil;
import feign.form.util.CharsetUtil;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.util.encoders.Base64;
import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletRequest;

/**
 * @author lengleng
 * @date 2019/2/1
 * 认证授权相关工具类
 */
@Slf4j
@UtilityClass
public class AuthUtils {
	private final String BASIC_ = "Basic ";

	/**
	 * 从header 请求中的clientId/clientsecect
	 *
	 * @param header header中的参数
	 */
	@SneakyThrows
	public String[] extractAndDecodeHeader(String header) {

		byte[] base64Token = header.substring(6).getBytes("UTF-8");
		byte[] decoded;
		try {
			decoded = Base64.decode(base64Token);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(
				"Failed to decode basic authentication token");
		}

		String token = new String(decoded, CharsetUtil.UTF_8);

		int delim = token.indexOf(":");

		if (delim == -1) {
			throw new RuntimeException("Invalid basic authentication token");
		}
		return new String[]{token.substring(0, delim), token.substring(delim + 1)};
	}

	/**
	 * *从header 请求中的clientId/clientsecect
	 *
	 * @param request
	 * @return
	 */
	@SneakyThrows
	public String[] extractAndDecodeHeader(HttpServletRequest request) {
		String header = request.getHeader(HttpHeaders.AUTHORIZATION);

		if (header == null || !header.startsWith(BASIC_)) {
			throw new RuntimeException("请求头中client信息为空");
		}

		return extractAndDecodeHeader(header);
	}


	public static DmUser getUser(){
        HttpServletRequest request = WebUtil.getRequest();
        if(request == null){
            return null;
        }else {
            Claims claims = getClaims(request);
            DmUser dmUser = new DmUser();
            dmUser.setId(claims.get("userId").toString());
            dmUser.setAccount(claims.get("account").toString());
            dmUser.setTenantId(claims.get("tenantId").toString());
            dmUser.setName(claims.get("username").toString());
            return dmUser;
        }
    }
    public static Claims getClaims(HttpServletRequest request) {
        String auth = request.getHeader("Authorization");
        String token;
        if (StringUtils.isNotBlank(auth)) {
            token = JwtUtil.getToken(auth);
            if (StringUtils.isNotBlank(token)) {
                return JwtUtil.parseJWT(token);
            }
        } else {
            token = request.getParameter("Authorization");
            if (StringUtils.isNotBlank(token)) {
                return JwtUtil.parseJWT(token);
            }
        }

        return null;
    }


}
